<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-suffix=":">
        <el-form-item label="是否启用" prop="status">
          <el-select
            v-model="queryParams.status"
            class="!w-[192px]"
            clearable
            placeholder="全部"
            @change="getTableData()"
          >
            <el-option label="全部" value="" />
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getTableData()">查询</el-button>
          <el-button type="warning" @click="handleAdd()" v-hasPerm="'sys:messageConfig:edit'">
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never">
      <el-table :data="tableData" style="width: 100%" show-overflow-tooltip>
        <el-table-column prop="msgType" label="消息类型" align="center">
          <template #default="{ row }">
            {{ row.msgType }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="接收目标类型" prop="receiveType">
          <template #default="scope">
            <el-tag v-if="scope.row.receiveType == 0" type="warning">全体</el-tag>
            <div v-if="scope.row.receiveType == 1">
              <!-- 显示前1个，多余的用...表示 -->
              <el-tag
                v-for="id in scope.row.receiveRoleIds.split(',').slice(0, 1)"
                :key="id"
                class="mr-2"
              >
                <!-- 根据id查名字 -->
                {{ getRoleName(id) }}
              </el-tag>
              <el-tooltip
                v-if="scope.row.receiveRoleIds.length > 1"
                :content="
                  scope.row.receiveRoleIds
                    .split(',')
                    .slice(1)
                    .map((item: string) => getRoleName(item))
                    .join(',')
                "
              >
                <el-tag class="mr-2">...</el-tag>
              </el-tooltip>
            </div>
            <div v-if="scope.row.receiveType == 2">
              <el-tag
                v-for="id in scope.row.receiveUserIds.split(',').slice(0, 1)"
                :key="id"
                class="mr-2"
              >
                <!-- 根据id查名字 -->
                {{ getUserName(id) }}
              </el-tag>
              <el-tooltip
                v-if="scope.row.receiveUserIds.length > 1"
                :content="
                  scope.row.receiveUserIds
                    .split(',')
                    .slice(1)
                    .map((item: string) => getUserName(item))
                    .join(',')
                "
              >
                <el-tag class="mr-2">...</el-tag>
              </el-tooltip>
            </div>
            <div v-if="scope.row.receiveType == 3">
              <el-tag
                v-for="role in scope.row.receiveRoleIds.split(',').slice(0, 1)"
                :key="role"
                class="mr-2"
                type="success"
              >
                {{ getRoleName(role) }}
              </el-tag>
              <el-tag
                v-for="user in scope.row.receiveUserIds.split(',').slice(0, 1)"
                :key="user"
                class="mr-2"
                type="success"
              >
                {{ getUserName(user) }}
              </el-tag>
              <el-tooltip
                v-if="scope.row.receiveRoleIds.length > 1"
                :content="
                  scope.row.receiveRoleIds
                    .split(',')
                    .slice(1)
                    .map((item: string) => getRoleName(item))
                    .join(',') +
                  ' ' +
                  scope.row.receiveUserIds
                    .split(',')
                    .slice(1)
                    .map((item: string) => getUserName(item))
                    .join(',')
                "
              >
                <el-tag class="mr-2">...</el-tag>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" />
        <el-table-column prop="createName" label="创建人" align="center" />
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              @click="handleEdit(row)"
              v-hasPerm="'sys:messageConfig:edit'"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(row)"
              v-hasPerm="'sys:messageConfig:del'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getTableData()"
      />
    </el-card>

    <!-- 配置对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增配置' : '编辑配置'"
      width="600px"
      @close="handleClose"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="消息类型" prop="msgType">
          <el-input
            v-noSpace
            v-model="formData.msgType"
            placeholder="请自定义消息类型名称"
            maxlength="10"
          />
        </el-form-item>
        <el-form-item label="目标类型" prop="receiveType">
          <!-- 全选 -->
          <el-checkbox v-model="formData.selectAll" @change="handleSpecifiedChange('all')">
            全选
          </el-checkbox>

          <!-- 指定角色 -->
          <el-checkbox v-model="formData.specifiedRole" @change="handleSpecifiedChange('role')">
            指定角色
          </el-checkbox>

          <!-- 指定用户 -->
          <el-checkbox v-model="formData.specifiedUser" @change="handleSpecifiedChange('user')">
            指定用户
          </el-checkbox>
        </el-form-item>
        <el-form-item
          v-if="formData.selectAll == false && formData.specifiedRole == true"
          label="指定角色"
          prop="receiveRoleIds"
        >
          <el-select v-model="formData.receiveRoleIds" multiple search placeholder="请选择指定角色">
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="formData.selectAll == false && formData.specifiedUser == true"
          label="指定用户"
          prop="receiveUserIds"
        >
          <el-select v-model="formData.receiveUserIds" multiple search placeholder="请选择指定用户">
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-switch v-model="formData.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import RoleAPI from "@/api/system/role";
import UserAPI, { Role, UserPageVO } from "@/api/system/user";
import MessageConfigAPI, {
  MessageConfigForm,
  MessageConfigList,
  MessageConfigQuery,
} from "@/api/system/messageConfig";
// 表格数据
const tableData = ref<MessageConfigList[]>([]);
const total = ref(0);
// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const formRef = ref<FormInstance>();
const queryParams = reactive<MessageConfigQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 表单数据
const formData = ref<
  MessageConfigForm & { selectAll: boolean; specifiedRole: boolean; specifiedUser: boolean }
>({
  id: NaN,
  msgType: "",
  receiveRoleIds: [],
  receiveUserIds: [],
  status: 0,
  createTime: "",
  updateTime: "",
  selectAll: false,
  specifiedRole: false,
  specifiedUser: false,
  publisherName: "",
  receiveType: NaN,
});

// 表单校验规则
const formRules = reactive<FormRules>({
  msgType: [
    { required: true, message: "请输入消息类型", trigger: "blur" },
    {
      max: 50,
      message: "消息类型不能超过50个字符",
    },
  ],
  receiveType: [{ required: true, message: "请选择目标类型", trigger: "change" }],
  receiveRoleIds: [{ required: true, message: "请选择接收角色", trigger: "change" }],
  receiveUserIds: [{ required: true, message: "请选择接收用户", trigger: "change" }],
});

// 角色选项
const roleOptions = ref<Role[]>([]);
// 用户选项
const userOptions = ref<UserPageVO[]>([]);
// 获取用户名
const getUserName = (id: string) => {
  return userOptions.value.find((item) => item.id === Number(id))?.name;
};
// 获取角色名
const getRoleName = (id: string) => {
  return roleOptions.value.find((item) => item.id === Number(id))?.roleName;
};

// 获取表格数据
const getTableData = () => {
  // TODO: 调用API获取数据
  MessageConfigAPI.getMessageConfigList(queryParams).then((res) => {
    console.log(res, "表格数据");
    tableData.value = res.list;
    total.value = res.total;
  });
};

// 获取角色列表
const getRoleOptions = () => {
  // TODO: 调用API获取角色列表
  RoleAPI.getSysRoleList().then((res) => {
    console.log(res, "角色列表");

    roleOptions.value = res.list;
  });
};

// 获取用户列表
const getUserOptions = () => {
  // TODO: 调用API获取用户列表
  UserAPI.getPage({ pageNum: 1, pageSize: 1000 }).then((res) => {
    console.log(res, "用户列表");
    userOptions.value = res.list;
  });
};

// 新增配置
const handleAdd = () => {
  dialogType.value = "add";
  dialogVisible.value = true;
  formData.value = {
    id: NaN,
    msgType: "",
    receiveRoleIds: [],
    receiveUserIds: [],
    status: 0,
    createTime: "",
    updateTime: "",
    selectAll: false,
    specifiedRole: false,
    specifiedUser: false,
    publisherName: "",
    receiveType: NaN,
  };
};

// 编辑配置
const handleEdit = (row: any) => {
  dialogType.value = "edit";
  dialogVisible.value = true;
  formData.value = { ...row };
  formData.value.msgType = formData.value.msgType;
  formData.value.receiveType = formData.value.receiveType;
  formData.value.specifiedRole = formData.value.receiveType == 1 || formData.value.receiveType == 3;
  formData.value.specifiedUser = formData.value.receiveType == 2 || formData.value.receiveType == 3;
  formData.value.selectAll = formData.value.receiveType == 0;
  formData.value.receiveRoleIds = row.receiveRoleIds
    ? row.receiveRoleIds.split(",").map(Number)
    : [];
  formData.value.receiveUserIds = row.receiveUserIds
    ? row.receiveUserIds.split(",").map(Number)
    : [];
};

// 删除配置
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm("确认删除该配置吗？", "提示", {
      type: "warning",
    });
    // TODO: 调用删除API
    MessageConfigAPI.deleteMessageConfig(row.id).then((res) => {
      console.log(res);
      ElMessage.success("删除成功");
      getTableData();
    });
  } catch (error) {
    console.error("删除失败:", error);
  }
};

// 状态变更
const handleStatusChange = async (row: any) => {
  try {
    // TODO: 调用更新状态API
    MessageConfigAPI.updateMessageConfigStatus(row.id, row.status).then((res) => {
      console.log(res);
      ElMessage.success("状态更新成功");
      getTableData();
    });
  } catch (error) {
    console.error("状态更新失败:", error);
  }
};

// 指定角色变更
const handleSpecifiedChange = (type: "all" | "role" | "user") => {
  if (type === "all") {
    formData.value.selectAll = true;
    formData.value.specifiedRole = false;
    formData.value.specifiedUser = false;
    formData.value.receiveRoleIds = [];
    formData.value.receiveUserIds = [];
    formData.value.receiveType = 0;
    return;
  }
  formData.value.selectAll = false;
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const params: any = { ...formData.value };
        if (formData.value.selectAll) {
          params.receiveType = 0;
          params.receiveRoleIds = "";
          params.receiveUserIds = "";
        } else {
          if (formData.value.specifiedUser && formData.value.specifiedRole) {
            params.receiveType = 3;
            //传递字符串
            params.receiveRoleIds = formData.value.receiveRoleIds.join(",");
            params.receiveUserIds = formData.value.receiveUserIds.join(",");
          } else if (formData.value.specifiedUser) {
            params.receiveType = 2;
            //传递字符串
            params.receiveUserIds = formData.value.receiveUserIds.join(",");
            params.receiveRoleIds = "";
          } else if (formData.value.specifiedRole) {
            params.receiveType = 1;
            //传递字符串
            params.receiveRoleIds = formData.value.receiveRoleIds.join(",");
            params.receiveUserIds = "";
          }
        }
        if (dialogType.value === "add") {
          // TODO: 调用新增API
          MessageConfigAPI.addMessageConfig(params).then((res) => {
            console.log(res);
            ElMessage.success(`新增成功`);
            dialogVisible.value = false;
            getTableData();
          });
        } else {
          // TODO: 调用更新API
          MessageConfigAPI.updateMessageConfig(params).then((res) => {
            console.log(res);
            ElMessage.success(`更新成功`);
            dialogVisible.value = false;
            getTableData();
          });
        }
      } catch (error) {
        console.error("提交失败:", error);
      }
    }
  });
};

// 关闭对话框
const handleClose = () => {
  formRef.value?.clearValidate();
  formRef.value?.resetFields();

  formData.value.receiveUserIds = [];
  formData.value.receiveRoleIds = [];
  formData.value.selectAll = false;
  formData.value.specifiedRole = false;
  formData.value.specifiedUser = false;
  formData.value.receiveType = NaN;
  dialogVisible.value = false;
};

// 初始化
onMounted(() => {
  getTableData();
  getRoleOptions();
  getUserOptions();
});
</script>
